<template>
  <form action="/">
    <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
    />
  </form>

  <van-divider content-position="left">已选标签</van-divider>
  <div v-if="activeIds.length === 0">请选择标签</div>
  <van-row gutter="16" style="padding: 0 16px">
    <van-col v-for="tag in activeIds">
      <van-tag closeable size="small" type="primary" @close="doClose(tag)">
        {{tag}}
      </van-tag>
    </van-col>
  </van-row>

  <van-divider content-position="left">选择标签</van-divider>
  <van-tree-select
      v-model:active-id="activeIds"
      v-model:main-active-index="activeIndex"
      :items="tagList"
  />
  <div style="padding: 16px">
    <van-button type="primary" block @click="doSearchResult">确认修改</van-button>
  </div>
</template>

<script setup lang="ts">
import {onMounted, ref} from "vue";
import myAxios from "../plugins/myAxios.js";
import {showFailToast, showSuccessToast} from "vant";
import {getCurrentUser} from "../services/user";
import {useRoute, useRouter} from "vue-router";

const router = useRouter();
const route = useRoute();

//所有标签
const originTagList = [{
  text: '性别',
  children: [
    {text: '男', id: '男'},
    {text: '女', id: '女'},
  ],
},
  {
    text: '精通位置',
    children: [
      {text: '上路战士', id: '上路战士'},
      {text: '中路法师', id: '中路法师'},
      {text: '打野刺客', id: '打野刺客'},
      {text: '射手ad', id: '射手ad'},
      {text: '辅助坦克', id: '辅助坦克'},
      {text: '全能大师', id: '全能大师'},
    ],
  },
];

//标签列表
let tagList = ref(originTagList);
//左侧索引
const activeIndex = ref(0);
//右侧索引，已选中的标签
const activeIds = ref([]);
const editTags = ref({
  currentValue: route.query.currentValue,
})
const searchText = ref('');
//将原有标签放入已选中的标签 activeIds
/*onMounted(() => {
  const currentTags = editTags.value.currentValue + '';
  activeIds.value = JSON.parse(currentTags);
})*/
const onSearch = (val) => {
  tagList.value = originTagList.map(parentTag => {
    const tempChildren = [...parentTag.children];
    const tempParentTag = {...parentTag};
    tempParentTag.children = tempChildren.filter(item => item.text.includes(searchText.value));
    return tempParentTag;
  });
}
const onCancel = () => {
  searchText.value = '';
  tagList.value = originTagList;
};
//移除标签
const doClose = (tag) => {
  activeIds.value = activeIds.value.filter(item => {
    return item !== tag;
  })
}

//修改标签
const doSearchResult = async () => {
  console.log("修改标签");
  const currentUser = await getCurrentUser();
  const res = await myAxios.post("/user/updateTags", {
    id: currentUser.id,
    tags: activeIds.value
  });
  if (res.data != null) {
    showSuccessToast("修改成功");
    router.replace("/user/update");
    // router.push("/user/login");
    // 跳转到之前的页面
    // const redirectUrl = route.query?.redirect?? '/';
    // window.location.href = redirectUrl;
    // router.replace("/")
  } else {
    showFailToast(res.data.description)
  }
};
</script>

<style scoped>

</style>